package com.lv.suyiyong.hfr.ui

import android.view.View
import android.view.View.OnClickListener
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SizeUtils
import com.lv.common.base.BaseActivity
import com.lv.common.imp.OnPositionTListener
import com.lv.common.ktx.LoadSrc
import com.lv.common.ktx.initSingleClickListener
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.MyUtils
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.showToast
import com.lv.common.widget.recyclerview.CenterHorizontalSmoothScroller
import com.lv.common.widget.recyclerview.decoration.SpacesItemDecoration
import com.lv.service.bean.BrandAttachedBean
import com.lv.service.bean.BrandItemBean
import com.lv.service.bean.BrandPageBean
import com.lv.service.model.ServiceViewModel
import com.lv.service.net.BrandHotBody

import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onFailure
import com.lv.service.network.onSuccess
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.adapter.HotSalerParentAdapter
import com.lv.suyiyong.hfr.adapter.HotSalerTabAdapter
import com.lv.suyiyong.hfr.databinding.ActivityBrandHotSalerBinding

import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2025/7/21 下午1:36
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 *
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：热卖
 */
@Route(path = ARoutUtils.BrandHotSalerActivity)
class BrandHotSalerActivity : BaseActivity<ActivityBrandHotSalerBinding>(),
    OnClickListener {

    //    @Autowired(name = "cpyid")
//    @JvmField
//    var mCpyid: String = ""
    private var mBrandId: String = ""
    private var mOrderBy: String = ""
    private var mTabPosition: Int = 0
    private var mFristLoad = true
    private var mClickTabAutoScroll = false
    private val mTopLeftUrl =
        "https://suyiyong.oss-cn-hangzhou.aliyuncs.com/iOS/projectPic/hfr/icon_brand_hot_sale.png"

    //    private var mScrollY = 0
//    private var changeScrollHeight: Int = SizeUtils.dp2px(100.0f)
    private val mBeans = mutableListOf<BrandItemBean>()
    private val mTabBeans = mutableListOf<BrandAttachedBean>()
    private var mTabAdapter: HotSalerTabAdapter? = null
    private var mAdapter: HotSalerParentAdapter? = null
    private var page: Int = 1
    private var pageSize: Int = 10000
    private val viewModel: ServiceViewModel by viewModel()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())

    override fun getLayoutRes() = R.layout.activity_brand_hot_saler
    override fun initView() {
        super.initView()
        initStatusBar(this, true, false)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            StatusBarUtil.setHeightAndPadding(this@BrandHotSalerActivity, ivTitlePage)
            StatusBarUtil.setHeightAndPadding(this@BrandHotSalerActivity, ivBackPage)
            initSingleClickListener(ivBackPage)
        }
    }

//    fun getCompanyCypid(): String? {
//        return mCpyid
//    }


    override fun initConfig() {
        super.initConfig()
        mBinding.ivTitlePage.LoadSrc(mTopLeftUrl)
//        showLoadErrorView("加载中……", showBack = true) {
//            finish()
//        }
        initAdapter()
        brandHot()
    }


//    private fun initPage() {
//        loadFinished()
//        initAdapter()
//
//    }


    private fun initAdapter() {

        mAdapter = HotSalerParentAdapter(mBeans)
        mBinding.rvContent.adapter = mAdapter
        mBinding.rvContent.addItemDecoration(
            SpacesItemDecoration(
                SizeUtils.dp2px(5.0f), SizeUtils.dp2px(5.0f), false
            )
        )
        mAdapter?.onViewItemClickListener = OnPositionTListener { position, data ->
            val brandid = data?.id
            ARouter.getInstance().build(ARoutUtils.BrandHotSalerChildActivity)
                .withString("brandid", brandid).navigation()
        }
        mTabAdapter = HotSalerTabAdapter(mTabBeans)
        mBinding.rvTab.adapter = mTabAdapter
        mTabAdapter?.onViewItemClickListener = OnPositionTListener { position, data ->
            if (mTabPosition == position) {
                return@OnPositionTListener
            }
            if (position == 0) {
                mBinding.rvTab.visibility = View.GONE
            }
            for (i in 0 until mTabBeans.size) {
                if (mTabBeans[i].selected == true) {
                    mTabBeans[i].selected = false
                    mTabAdapter?.notifyItemChanged(i, R.id.tv_name)
                }
            }
            mTabBeans[position].selected = true
            mTabAdapter?.notifyItemChanged(position, R.id.tv_name)
            mTabPosition = position
            scrollTabToCenter()
            mBrandId = mTabBeans[position].id ?: ""
            val positionContent = mBeans.indexOfFirst { it.id == mBrandId }
            scrollContentToCenter(positionContent)
        }

    }

//    private fun loadDate() {
//        mOrderBy = "0"
//        page = 1
//        brandHot()
//    }

    private fun brandHot() {
        startLoading()
        val body = BrandHotBody(page, pageSize, mBrandId, mOrderBy)
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async {
                    viewModel.brandHot(body)
                }
                    .await()
            parseBrandHotResult(result)
        }
    }

    private fun parseBrandHotResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<BrandPageBean> { code, data, message, result ->
                val items = data?.items
//                if (mOrderBy == "1") {
//                    items?.let {
//                        for (i in 0 until items.size) {
//                            mBeans.add(0, items[i])
//                        }
//                    }
//                } else {
//                    if (page == 1) {
//                        mBeans.clear()
//                    }
//                    items?.let { mBeans.addAll(it) }
//                }
                MyUtils.recyclerviewSetData(
                    page, pageSize, mBinding.refreshLayout, mBeans, items, mAdapter
                )
//                mAdapter?.notifyDataSetChanged()
//                if (page == 1 && mBeans.isNotEmpty()) {
//
////                    mBinding.rvTab.visibility = View.GONE
//                }
//                mBinding.refreshLayout.finishRefresh()
//                mBinding.refreshLayout.finishLoadMore()
                if (mBeans.isEmpty()) {
                    mAdapter?.setEmptyView(getEmptyCenterView(mBinding.rvContent, "暂无内容"))
                }
                if (mFristLoad) {
                    mFristLoad = false
                    val attached = data?.attached
                    mTabBeans.clear()
                    if (!attached.isNullOrEmpty()) {
                        mTabBeans.addAll(attached)
                        if (mBeans.isNotEmpty()) {
                            val id = mBeans[0].id
                            val position = mTabBeans.indexOfFirst { it.id == id }
                            if (position > 0) {
                                mTabBeans[position].selected = true
                                mBinding.rvTab.smoothScrollToPosition(position)
                            } else {
                                mTabBeans[0].selected = true
                            }
                        }
                    }
                    mTabAdapter?.notifyDataSetChanged()
                }
//                else {
//                    var position = -1
//                    if (mBeans.isNotEmpty()) {
//                        var id = "aaa"
//                        if (mOrderBy == "1") {
//                            if (!items.isNullOrEmpty()) {
//                                id = items[items.size - 1].id ?: ""
//                            }
//
//                        } else {
//                            id = mBeans[0].id ?: ""
//                            mScrollY = 0
//                        }
//                        position = mTabBeans.indexOfFirst { it.id == id }
//                        for (i in 0 until mTabBeans.size) {
//                            if (mTabBeans[i].selected == true) {
//                                mTabBeans[i].selected = false
//                                mTabAdapter?.notifyItemChanged(i, R.id.tv_name)
//                            }
//                        }
//                        if (position > 0) {
//                            mTabBeans[position].selected = true
//                            mBinding.rvTab.smoothScrollToPosition(position)
//                            mTabAdapter?.notifyItemChanged(position, R.id.tv_name)
//                            mTabPosition = position
//                            mScrollY = 0
//                            mBinding.rvContent.post {
//                                (mBinding.rvContent.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(
//                                    position, 0
//                                )
//                            }
//                        } else {
//                            mTabBeans[0].selected = true
//                            mTabAdapter?.notifyItemChanged(0, R.id.tv_name)
//                            mTabPosition = 0
//                            mScrollY = 0
//                            mBinding.rvContent.post {
//                                (mBinding.rvContent.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(
//                                    0, 0
//                                )
//                            }
//                        }
//                    }
//                }
            }
            onBizError<Any> { code, message, data ->
                mBinding.refreshLayout.finishRefresh()
                mBinding.refreshLayout.finishLoadMore()
                showToast(message)
            }
        }
        data.onFailure {
            mBinding.refreshLayout.finishRefresh()
            mBinding.refreshLayout.finishLoadMore()
        }
    }

    override fun initEvents() {
        super.initEvents()

        mBinding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                page = 1
                mOrderBy = "1"
                if (mTabPosition == 0) {
                    mOrderBy = "0"
                }
                mBrandId = mTabBeans[mTabPosition].id ?: ""
                brandHot()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                page++
                mOrderBy = "0"
                brandHot()
            }
        })
        val layoutManager = mBinding.rvContent.layoutManager as LinearLayoutManager
        mBinding.rvContent.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val isFirstItemVisible = layoutManager.findFirstCompletelyVisibleItemPosition() == 0

                if (isFirstItemVisible) {
                    // 滑动到顶部时的逻辑（如隐藏刷新按钮）
                    mBinding.rvTab.visibility = View.GONE
                } else {
                    // 未滑动到顶部时的逻辑（如显示刷新按钮）
                    mBinding.rvTab.visibility = View.VISIBLE
                }
//                if (mTabPosition == 0) {
//                    mBinding.rvContent.y
//                    mScrollY += dy
//                    val abss: Int = abs(mScrollY)
//                    var mAlpha = abss * 1.0f / changeScrollHeight
//                    if (mAlpha <= 0) {
//                        mAlpha = 0.0f
//                        mBinding.rvTab.visibility = View.GONE
//                    } else {
//                        mBinding.rvTab.visibility = View.VISIBLE
//                    }
//                    if (mAlpha > 1) {
//                        mAlpha = 1.0f
//                    }
////                var alpha = (scrollY - changeHeight) * 1.0f / changeScrollHeight
//                    mBinding.rvTab.alpha = mAlpha
//                }
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (mClickTabAutoScroll) {
                    return
                }
                val lastVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()
                if (lastVisibleItemPosition != RecyclerView.NO_POSITION && newState == RecyclerView.SCROLL_STATE_IDLE) {
//                    mClickTabAutoScroll = false
                    // 获取到了有效位置，可以使用这个位置来获取对应的条目数据
                    var lastVisibleItem: BrandItemBean? = null
                    try {
                        lastVisibleItem = mAdapter?.getItem(lastVisibleItemPosition)
                        val position =
                            mTabBeans.indexOfFirst { item -> item.id == lastVisibleItem?.id }
                        if (position >= 0 && position != mTabPosition) {
                            if (mTabPosition >= 0) {
                                mTabBeans[mTabPosition].selected = false
                                mTabAdapter?.notifyItemChanged(mTabPosition)
                            }
                            mTabBeans[position].selected = true
                            mBrandId = mTabBeans[position].id ?: ""
                            mTabPosition = position
                            mTabAdapter?.notifyItemChanged(mTabPosition)
                            scrollTabToCenter()

                        }

                    } catch (e: Exception) {
                    }
                }
            }
        })

        rigestEventBus()
    }

    private fun scrollTabToCenter() {
        //tab滑动
        val layoutManagerTab = mBinding.rvTab.layoutManager as LinearLayoutManager
        val smoothScroller =
            CenterHorizontalSmoothScroller(this)
        smoothScroller.targetPosition = mTabPosition
        layoutManagerTab.startSmoothScroll(smoothScroller)
    }

    private fun scrollContentToCenter(position: Int) {
        //tab滑动
        val layoutManagerTab = mBinding.rvContent.layoutManager as LinearLayoutManager
//        val smoothScroller =
//            CenterHorizontalSmoothScroller(this)
//        smoothScroller.targetPosition = position
//        layoutManagerTab.startSmoothScroll(smoothScroller)
        layoutManagerTab.scrollToPositionWithOffset(position, 0)
    }


    private fun rigestEventBus() {

    }

    override fun initData() {
        super.initData()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_back_page -> {
                finish()
            }

        }
    }


    override fun onDestroy() {
        super.onDestroy()
//        if (mHintDialog?.isShowing == true) {
//            mHintDialog?.dismiss()
//        }
    }
}